﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using SBS.Common;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;

namespace SBS.Common
{
   /// <summary>
   /// C# String 基础类库扩展
   /// </summary>   
    public static class StringExtension
    {
        public static string ToXmlSafeString(this string str)
        {
            XmlDocument Dom = new XmlDocument();
            XmlElement elem = Dom.CreateElement("root");
            elem.InnerText = str;            
            return elem.InnerXml;            
        }
        public static string FormatString(this string str, params object[] args)
        {
            return string.Format(str, args);
        }

        public static string Join(this string[] StrArr, string Sep)
        {
            return string.Join(Sep, StrArr);
        }

        /// <summary>
        /// 使用 XmlSerializer.Deserialize 反序列化当前字符串为指定类型的对象。
        /// 该方法位于 SBS.Common.dll
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="str">当前字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(this string str)
        {            
            XmlSerializer Serializer = new XmlSerializer(typeof(T));
            byte[] buf = Encoding.Default.GetBytes(str);
            MemoryStream stream = new MemoryStream(buf);
            return (T)Serializer.Deserialize(stream);            
        }

        /// <summary>
        /// 使用 DataContractSerializer.Deserialize 反序列化当前字符串为指定类型的对象。
        /// 该方法位于 SBS.Common.dll
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="str">当前字符串</param>
        /// <returns></returns>
        public static T DeserializeToData<T>(this string str)
        {
            DataContractSerializer Serializer = new DataContractSerializer(typeof(T));
            byte[] buf = Encoding.Default.GetBytes(str);
            MemoryStream stream = new MemoryStream(buf);
            return (T)Serializer.ReadObject(stream);
        }
        
        /// <summary>
        /// 把Uri中的查询部分转换为字典
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static Dictionary<string, string> QueryStringToDictionary(this Uri uri)
        {
            string QueryString = uri.Query;
            if (string.IsNullOrEmpty(QueryString)) return null;
            return SBS.Common.Utility.QueryStringToDictionary(QueryString);                                   
        }
 
    }
   
}
